import { h, resolveComponent } from 'vue'
import { getComponents, getRouteName } from '/@/utils/helper'
import menuConfig from '/@/config/menu'

const components = getComponents(
  import.meta.glob('../../pages/**/*.vue')
)

const routes = [
  {
    path: '/reset-pwd',
    name: 'ResetPwd',
    component: () => import('/@/pages/me/ResetPwd.vue'),
    meta: {
      title: '修改密码'
    }
  }
]
let indexRoute

function renderIcon(icon) {
  return () => h(
    resolveComponent('n-icon'), null, {
      default: () => h(icon)
    })
}

function renderRouterLink(title, to) {
  return () => h(
    resolveComponent('router-link'), {
      class: ['menu-router-link'], to
    }, {
      default: () => title
    })
}

const menuRoutes = []

function walker(
  route,
  parentPath = '/',
  rawBreadcrumb = [],
  rawExpandedKeys = []
) {
  const {
    title,
    icon,
    children = [],
    // visible in menus
    hidden = false,
    path: rawPath,
    component: rawComponent,
    ...routeProps
  } = route

  let path

  if (rawPath.startsWith('/')) {
    path = rawPath
  } else if (rawPath) {
    path = `${parentPath}/${rawPath}`.replace(/\/+/g, '/')
  } else {
    path = parentPath
  }

  const menuItem = {
    key: path,
    children: []
  }

  if (icon) {
    menuItem.icon = renderIcon(icon)
  }

  const breadcrumb = [...rawBreadcrumb, { title, to: path }]
  const expandedKeys = [...rawExpandedKeys, path]

  if (Array.isArray(children) && children.length) {
    children.forEach(v => {
      const subMenuItem = walker(v, path, breadcrumb, expandedKeys)

      if (subMenuItem) {
        menuItem.children.push(subMenuItem)
      }
    })
  }

  menuItem.rawTitle = title

  if (menuItem.children.length === 0) {
    menuItem.label = renderRouterLink(title, path)
    delete menuItem.children
  } else {
    menuItem.label = title
  }

  const menuRoute = {
    path,
    name: getRouteName(path),
    meta: {
      title,
      breadcrumb,
      expandedKeys,
      ...routeProps
    }
  }
  const component = rawComponent || components[path]

  if (component) {
    menuRoute.component = component
    menuRoutes.push(menuRoute)

    if (!indexRoute) {
      indexRoute = menuRoute
    }
  } else if (menuItem.children?.length) {
    menuRoute.redirect = menuItem.children[0]?.key
    menuRoutes.unshift(menuRoute)
  }

  if (!hidden) {
    return menuItem
  }
}

export const menuOptions = menuConfig.map(v => walker(v))

export { indexRoute }

export default [
  ...routes,
  ...menuRoutes
]
